package cn.com.anypay.manager.common.validation;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * 商户ID格式验证器实现
 */
public class MerchantIdFormatValidator implements ConstraintValidator<MerchantIdFormat, String> {

    private int minLength;
    private int maxLength;
    private boolean allowStartWithDigit;

    @Override
    public void initialize(MerchantIdFormat constraintAnnotation) {
        this.minLength = constraintAnnotation.minLength();
        this.maxLength = constraintAnnotation.maxLength();
        this.allowStartWithDigit = constraintAnnotation.allowStartWithDigit();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null || value.trim().isEmpty()) {
            return false;
        }

        // 检查长度
        if (value.length() < minLength || value.length() > maxLength) {
            return false;
        }

        // 检查字符格式：只能包含大写字母和数字
        if (!Pattern.matches("^[A-Z0-9]+$", value)) {
            return false;
        }

        // 检查是否以数字开头（如果不允许）
        if (!allowStartWithDigit && Character.isDigit(value.charAt(0))) {
            return false;
        }

        return true;
    }
}